package com.easysoft.commons.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件检查工具类
 * 
 * @author try
 *
 */
public final class CheckFile {

	private static final String[] gif = { "47", "49", "46", "38" };
	private static final String[] jpg = { "ff", "d8", "ff", "e0" };
	private static final String[] png = { "89", "50", "4e", "47" };
	private static final String[] bpm = { "42", "4d" };

	private static final String[][] picture = { gif, jpg, png, bpm };

	private CheckFile() {
	}

	/**
	 * 判断文件是否真的为图片文件(gif/jpg/png/bpm)
	 * 
	 * @param pathname
	 *            文件路径
	 * @return ture:图片;false:非图片
	 */
	public static boolean isPicture(String pathname) {
		File file = new File(pathname);
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			int firstbyte = -1;
			if ((firstbyte = in.read()) != -1) {
				String firsthex = Integer.toHexString(firstbyte);
				int secondbyte = -1;
				String secondhex = null;
				for (int i = 0; i < picture.length; i++) {
					if (picture[i][0].equals(firsthex)) {
						sec: for (int j = 1; j < picture[i].length; j++) {
							if ((secondbyte = in.read()) != -1) {
								secondhex = Integer.toHexString(secondbyte);
								if (!picture[i][j].equals(secondhex)) {
									break sec;
								}
							}
						}
						return true;
					}
				}
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (in != null) {
					in.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	
	/**
	 * 判断文件是否真的为图片文件(gif/jpg/png/bpm)
	 * 
	 * @param pathname
	 *            文件路径
	 * @return ture:图片;false:非图片
	 */
	public static boolean isPicture(InputStream in) {
		try {
			int firstbyte = -1;
			if ((firstbyte = in.read()) != -1) {
				String firsthex = Integer.toHexString(firstbyte);
				int secondbyte = -1;
				String secondhex = null;
				for (int i = 0; i < picture.length; i++) {
					if (picture[i][0].equals(firsthex)) {
						sec: for (int j = 1; j < picture[i].length; j++) {
							if ((secondbyte = in.read()) != -1) {
								secondhex = Integer.toHexString(secondbyte);
								if (!picture[i][j].equals(secondhex)) {
									break sec;
								}
							}
						}
						return true;
					}
				}
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (in != null) {
					in.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	
}
